#!/bin/bash

# 多服务容器启动脚本
set -e

echo "Starting multi-service container..."

# 初始化MySQL数据目录
if [ ! -d "/var/lib/mysql/mysql" ]; then
    echo "Initializing MySQL database..."
    mysqld --initialize-insecure --user=mysql
fi

# 启动MySQL服务
echo "Starting MySQL service..."
service mysql start

# 等待MySQL启动
echo "Waiting for MySQL to be ready..."
for i in {1..30}; do
    if mysqladmin ping -h localhost -u root --silent; then
        echo "MySQL is ready!"
        break
    fi
    echo "Waiting for MySQL... ($i/30)"
    sleep 2
done

# 配置MySQL用户和权限
echo "Configuring MySQL..."
mysql -u root -e "
    ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
    CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY '123456';
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
"

# 启动Redis服务
echo "Starting Redis service..."
service redis-server start

# 等待Redis启动
echo "Waiting for Redis to be ready..."
for i in {1..30}; do
    if redis-cli -a 123456 ping > /dev/null 2>&1; then
        echo "Redis is ready!"
        break
    fi
    echo "Waiting for Redis... ($i/30)"
    sleep 2
done

# 启动supervisor管理所有服务
echo "Starting supervisor..."
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf 